import 'package:duuchin/components/singer_card.dart';
import 'package:duuchin/models/user_model.dart';
import 'package:duuchin/services/user_service.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class SingerPage extends StatefulWidget {
  const SingerPage({Key key}) : super(key: key);

  @override
  _SingerPageState createState() => _SingerPageState();
}

class _SingerPageState extends State<SingerPage> {
  List<UserItem> _singList = UserList([]).list;
  int page = 1;
  int limit = 10;
  bool error = false;
  String errorMsg = '';

  @override
  void initState() {
    super.initState();
    _getSings();
  }

  Future _getSings({bool addpush = false}) async {
    try {
      Map<String, dynamic> result =
          await UserService.getUsers(page: page, limit: limit);
      UserList userListModel = UserList.fromJson(result['data']);
      setState(() {
        page++;
        if (addpush) {
          _singList.addAll(userListModel.list);
        } else {
          _singList = userListModel.list;
        }
      });
    } catch (e) {
      setState(() {
        error = true;
        errorMsg = e.toString();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
        itemCount: _singList.length,
        padding: EdgeInsets.all(5),
        gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
          mainAxisExtent: MediaQuery.of(context).size.width / 1.55,
          maxCrossAxisExtent: MediaQuery.of(context).size.width / 2,
          mainAxisSpacing: 8,
          crossAxisSpacing: 7,
        ),
        itemBuilder: (BuildContext context, int index) {
          return Container(
            padding: EdgeInsets.all(7),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(4.0)),
            ),
            child: SingerCard(
              coverPictureUrl: _singList[index].coverPictureUrl,
              nickname: _singList[index].nickname,
              musicCount: _singList[index].musicCount,
              musicPlayCount: _singList[index].musicPlayCount,
            ),
          );
        });
  }
}
